import { signTeamPay, signTeamPayCancel } from '@/api';
import type { SignTeam } from '@/api/data';

// 支付
export const payOrder = (
  params: Pick<SignTeam.Leader.Data, 'order_id' | 'order_sn'>,
  cb?: (type: 'success' | 'fail') => void
) => {
  uni.showLoading({
    title: '支付中...',
    mask: true,
  });
  // 支付
  signTeamPay({ ...params, wx_code: uni.getStorageSync('wx_code') || '' })
    .then(res => {
      const payData = res.data;
      if (payData?.timeStamp) {
        uni.showModal({
          title: '提示',
          content: `${res?.msg}`,
          showCancel: false,
          success: m => {
            if (m.confirm) {
              uni.requestPayment({
                provider: 'wxpay',
                orderInfo: {},
                nonceStr: res.data?.nonceStr, // 随机字符串
                package: res.data?.package, // 固定值
                signType: res.data?.signType,
                timeStamp: res.data?.timeStamp, // 时间戳（单位：秒）
                paySign: res.data?.paySign, // 签名，这里用的 MD5/RSA 签名
                success: function (res) {
                  cb?.('success');
                },
                fail: function (err) {
                  cb?.('fail');
                },
              });
            }
          },
        });
      } else {
        uni.showModal({
          title: '提示',
          content: res?.msg || '支付失败',
          showCancel: false,
        });
      }
    })
    .catch(e => {
      uni.showModal({
        title: '提示',
        content: e?.msg || '支付失败',
        showCancel: false,
      });
    })
    .finally(() => {
      uni.hideLoading();
    });
};

// 取消支付
export const cancelPayOrder = (
  params: Pick<SignTeam.Leader.Data, 'order_id' | 'order_sn'>,
  cb?: () => void
) => {
  uni.showModal({
    title: '提示',
    content: '是否取消支付？',
    success: res => {
      if (res.confirm) {
        // 关闭支付
        signTeamPayCancel({
          order_id: params.order_id || '',
          order_sn: params.order_sn || '',
        }).then(res => {
          uni.showModal({
            title: '提示',
            content: res?.msg || '取消支付成功',
            showCancel: false,
            success: res => {
              if (res.confirm) {
                if (cb) {
                  cb();
                } else {
                  uni.switchTab({ url: '/pages/index/index' });
                }
              }
            },
          });
        });
      }
    },
  });
};
